/**
 * <p>Package : org.tea.springdata.mina.test</p>
 * <p>E-Mail : ztlyde@gmail.com</p>
 */
package org.tea.springdata.mina.test;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author: John zhang
 * @version: 0.1
 */
public class SocketClient {

	public static void main(String args[]) {
		Socket client = new Socket();
		try {
			client.connect( new InetSocketAddress( "localhost", 4848));
			
			DataInputStream resp = new DataInputStream( client.getInputStream() );
			DataOutputStream req = new DataOutputStream( client.getOutputStream());
			BufferedReader message = new BufferedReader( new InputStreamReader( System.in ) );
			while( true ) {
				String content = message.readLine();
				// req.write( ( "\n".getBytes() ) );
				// req.writeChars( content.getBytes() + "\0" );
				req.writeBytes( content + '\0' );
				req.flush();
				
				StringBuilder result = new StringBuilder();

				char[] lineBuffer = null;
				char[] buf = lineBuffer =  new char[ 128 ];
				int offset = 0;
				for( int read = resp.read() ; read != '\0' ; read = resp.read() ) {
					buf[offset++] = (char) read;
					if( offset == buf.length ) {
						buf = new char[ offset + 128 ];
						System.arraycopy( lineBuffer, 0, buf, 0, offset );
						lineBuffer = buf;
					}
				}
				result.append( String.copyValueOf( buf, 0, offset ) );
				System.out.println( "client receive message is : " + result.toString() );
					
			}
		} catch ( Exception e ) {
			e.printStackTrace();
		}
		
	}
}
